package com.czp.dict.service.impl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.ibatis.session.RowBounds;

import com.czp.dict.mapper.IDictMapper;
import com.czp.dict.model.Dict;
import com.czp.dict.model.DictType;
import com.czp.dict.service.IDictService;
import com.czp.framework.model.DataStoreTemplate;
import com.czp.framework.util.DateUtils;
import com.google.gson.Gson;

/**
 * 【环 境】：J2SE 1.7
 * @author   柴志鹏	CHAIZP@GMAIL.COM
 * @version  version 1.0
 * @since    2014-8-5
 */
public class DictServiceImpl implements IDictService {
	private IDictMapper dictMapper;
	private Gson gson = new Gson();
	
	public String getDictTypeList(DictType dictType) throws Exception {
		RowBounds bounds = new RowBounds(dictType.getStart(), dictType.getLimit());
		DataStoreTemplate dst = new DataStoreTemplate();
		dst.setList(dictMapper.getDictTypeList(dictType, bounds));
		dst.setTotal(dictMapper.getDictTypeCount(dictType));
		return gson.toJson(dst);
	}
	
	public String getDictList(Dict dict) throws Exception {
		RowBounds bounds = new RowBounds(dict.getStart(), dict.getLimit());
		DataStoreTemplate dst = new DataStoreTemplate();
		dst.setList(dictMapper.getDictList(dict, bounds));
		dst.setTotal(dictMapper.getDictCount(dict));
		return gson.toJson(dst);
	}
	
	public int dictTypeController(DictType dictType) throws Exception {
		dictType.setModifyDate(DateUtils.getSysTimestamp());
		if(dictType.getCudType().equals("C")) {//添加
			return dictMapper.insertDictType(dictType);
		} else if(dictType.getCudType().equals("U")) {//修改
			return dictMapper.updateDictType(dictType);
		} else if(dictType.getCudType().equals("D")) {//删除
			return dictMapper.deleteDictType(dictType);
		}
		return 0;
	}
	
	public int dictController(String jsonData) throws Exception {
		JSONArray jsonArr = JSONArray.fromObject(jsonData);
		if(jsonArr == null || jsonArr.isEmpty()) {
			return 0;
		}
		Dict dict = new Dict();
		int i = 0;
		for(int cnt = jsonArr.size(); i < cnt; i++) {
			JSONObject jsonObj = jsonArr.getJSONObject(i);
			dict = (Dict) JSONObject.toBean(jsonObj, dict.getClass());
			if(dict.getCudType().equals("C")) {//添加
				dictMapper.insertDict(dict);
			} else if(dict.getCudType().equals("U") && !"".equals(dict.getId())) {//修改
				dictMapper.updateDict(dict);
			} else if(dict.getCudType().equals("D") && !"".equals(dict.getId())) {//删除
				dictMapper.deleteDict(dict);
			} else {
				continue;
			}
		}
		return i;
	}
	
	/**
	 * 获取 dictMapper
	 * @return 返回 dictMapper
	 */
	public IDictMapper getDictMapper() {
		return dictMapper;
	}
	/**
	 * 设置 dictMapper
	 * @param 对dictMapper进行赋值
	 */
	public void setDictMapper(IDictMapper dictMapper) {
		this.dictMapper = dictMapper;
	}
	
}
